package com.sk.app.util;

import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author Administrator
 * @FileName
 * @date 2019/2/19 13:28
 */
public class HttpUtils {
    /**
     * post提交form-data类型的数据name=value
     * @param httpUrl
     * @param map
     * @param fileMap
     * @return
     */
    public  static String postData(String httpUrl, Map<String, Object> map, Map<String, File> fileMap) {
        String result;  //返回的结果
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader in = null;
        //结束符【换行】
        String end = "\r\n";
        //分隔符开头字符
        String twoHyphens = "--";
        String boundary = "SJDASJODAODASSD";
        HttpURLConnection connection = null;
        try {
            URL url = new URL(httpUrl);
            //打开连接对象
            connection = (HttpURLConnection) url.openConnection();
            //允许输入流
            connection.setDoInput(true);
            //设置允许输出
            connection.setDoOutput(true);
            //设置不缓存
            connection.setUseCaches(false);
            // 连接超时为10秒
            connection.setConnectTimeout(10000);
            //设置请求方式
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("Charset", "UTF-8");
            // 设置请求数据类型并设置boundary部分；
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            connection.connect();//开启连接
            //获得输出流的对象
            DataOutputStream ds = new DataOutputStream(connection.getOutputStream());
            Set<Map.Entry<String, Object>> paramEntrySet = map.entrySet();
            Iterator paramIterator = paramEntrySet.iterator();
            while (paramIterator.hasNext()) {
                Map.Entry<String, Object> entry = (Map.Entry<String, Object>) paramIterator.next();
                String key = entry.getKey();
                Object value = entry.getValue();
//                Log.i("postData", "上传的key值为：" + key);
//                Log.i("postData", "上传的value信息为：" + URLEncoder.encode(value.toString(), "UTF-8"));
                //--SJDASJODAODASSD
                ds.writeBytes(twoHyphens + boundary + end);
                //Content-Disposition: form-data; name="key"
                ds.writeBytes("Content-Disposition: form-data;accept-charset=\"utf-8\"; " + "name=\"" + key + "\"" + end + end + URLEncoder.encode(value.toString(), "UTF-8"));
                ds.writeBytes(end);
            }
            if (!fileMap.isEmpty()) {
                for (String str : fileMap.keySet()) {
                    //取得key值
                    File file = fileMap.get(str);
                    Log.i("file",file.toString());
                    //--SJDASJODAODASSD
                    ds.writeBytes(twoHyphens + boundary + end);
                    //Content-Disposition: form-data; name="key"
                    ds.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + URLEncoder.encode(file.getName(), "UTF-8") + "\"" + end + "Content-Type: image/jpg" + end + end);
                    InputStream is = new FileInputStream(file);
                    // FileInputStream is = new FileInputStream(file);
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = is.read(bytes)) != -1) {
                        ds.write(bytes, 0, len);
                    }
                    is.close();
                    Log.i("postData", "上传的图片key值为：" + str);
                    ds.writeBytes(end);
                }
            }
            //--SJDASJODAODASSD
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
            //刷新数据
            ds.flush();
            ds.close();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            //获得响应状态码
            int statusCode = connection.getResponseCode();
            Log.i("postData", "postData:相应状态码： " + statusCode);
            if (statusCode == HttpURLConnection.HTTP_OK) {
                char[] buf = new char[1024];
                int len = -1;
                while ((len = in.read(buf, 0, buf.length)) != -1) {
                    stringBuilder.append(buf, 0, len);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.i("MalformedURLException", "IOException:"+e.toString());

        } catch (IOException e) {
            Log.i("postData", "postData: IOException:"+e.toString());
            e.printStackTrace();
        }
        result = stringBuilder.toString();
        Log.i("Post", "result===========>" + result);

        return result;
    }
}
